package web;

import pojo.Sport;
import pojo.SportItem;
import pojo.User;
import service.ItemService;
import service.SportService;
import service.impl.ItemServiceImpl;
import service.impl.SportServiceImpl;
import utils.webUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ItemServlet extends BaseServlet{

    private ItemService itemService = new ItemServiceImpl();
    private SportService sportService = new SportServiceImpl();

    //参赛
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数  商品编号
        int id = webUtils.parseInt(req.getParameter("id"), 0);
        //调用sportService.querysportById(id)返回图书信息

        //把图书信息转换为CartItem商品项

        User loginUser = (User) req.getSession().getAttribute("user");

        SportItem item = itemService.querysportItem(id, loginUser.getId());

        if (item == null) {
            Sport Sport = sportService.querysportById(id);
            SportItem sportItem = new SportItem(Sport.getId(), Sport.getName(), loginUser.getId(), loginUser.getUsername(), 0, 0);

            itemService.addItem(sportItem);
            //重定向回原来商品所在的地址页面
            resp.sendRedirect(req.getHeader("Referer"));
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }

    //打分
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int sportsid = webUtils.parseInt(req.getParameter("sportsid"), 0);
        int userid = webUtils.parseInt(req.getParameter("userid"), 0);
        double Scores = Double.parseDouble(req.getParameter("scores"));
        SportItem sportItem = itemService.querysportItem(sportsid, userid);
        sportItem.setScors(Scores);
        sportItem.setRank(1);
        itemService.updateItem(sportItem);

        //很可能有问题
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    protected void sportsId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int sportsid = webUtils.parseInt(req.getParameter("sportsid"), 0);
        List<SportItem> sportItems = itemService.queryItemsBySportsId(sportsid);
        req.setAttribute("sportItems",sportItems);
        req.getRequestDispatcher("/pages/Item/item.jsp").forward(req, resp);
    }

    protected void userId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = webUtils.parseInt(req.getParameter("userid"), 0);
        List<SportItem> sportItems = itemService.queryItemsByUserId(userId);
        req.setAttribute("sportItems",sportItems);
        req.getRequestDispatcher("/pages/Item/item.jsp").forward(req, resp);

    }







}
